package FredyCRUD;

import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 * Forma que lista las Bases de Datos
 * @author JF
 */
public class ListaBD extends javax.swing.JFrame {
    Conexion mySQLBD;                   // Parámetros de conexión a la BD
    
    /**
     * Creates new form ListaBD
     */
    public ListaBD() {
        initComponents();
    }

    /**
     * Crea nueva forma de ListaBD
     * @param usuario: Usuario de la BD
     * @param password: Contraseña de conexión a la BD
     * @param maquina: Máquina donde reside el DBMS
     * @param puerto: Puerto de conexión del DBMS
     */
    public ListaBD(String usuario, char[] password, String maquina, String puerto) {
        mySQLBD = new Conexion(maquina, puerto, usuario, new String(password));       
        initComponents();                       // Inicializa la forma
        
        if (mySQLBD.conectar("")) {             // Conexión a la BD
            if (mySQLBD.consultarBD()) {        // Consulta de BDs
                mostrarBD();                    // Mostrar el listado de BDs
            }
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        botAceptar = new javax.swing.JButton();
        comBD = new javax.swing.JComboBox();
        labBD = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("FredyCRUD: Escoger la BD");

        botAceptar.setText("Aceptar");
        botAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botAceptarActionPerformed(evt);
            }
        });

        comBD.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        labBD.setText("Base de datos");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(labBD, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(comBD, 0, 234, Short.MAX_VALUE)
                    .addComponent(botAceptar))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(51, 220, Short.MAX_VALUE)
                .addComponent(botAceptar)
                .addGap(57, 57, 57))
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labBD)
                    .addComponent(comBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Llamado a la forma de listar tablas
     * @param evt Evento al manipular el botón
     */
    private void botAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botAceptarActionPerformed
        try {
            mySQLBD.getResultado().close();     // Libera set de resultados
            mySQLBD.getConexion().close();      // cierra la conexión
            
            ListaTablas formaListaTablas = new ListaTablas(mySQLBD, 
                    comBD.getSelectedItem().toString());
            formaListaTablas.setVisible(true);  // Invoca a la forma de listar tablas
        } catch (SQLException ex) {             // Fallo al acceso de BDs
            JOptionPane.showMessageDialog(null, 
                    "Error!, no se encontraron BDs,\n[" + ex.getMessage() + "]");
        }
    }//GEN-LAST:event_botAceptarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListaBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListaBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListaBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListaBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ListaBD().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botAceptar;
    private javax.swing.JComboBox comBD;
    private javax.swing.JLabel labBD;
    // End of variables declaration//GEN-END:variables

    /**
     * Adiciona los nombres de las BDs en la lista de selección
     */
    private void mostrarBD() {
        comBD.removeAllItems();                     // Borra la lista de selección de items
        try {
            while (mySQLBD.getResultado().next()) { // Recorre las BDs
                comBD.addItem(mySQLBD.getResultado().getString(1));
            }
        } catch (SQLException ex) {                 // Error de listado de BDs
            JOptionPane.showMessageDialog(null, 
                    "Error!, no se encontraron BDs,\n[" + ex.getMessage() + "]");
        }
    }
}
